<?php
if(!empty($_POST)) {
  print_r($_POST);
}
?>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>

<script type="text/javascript">
  $(function(){


    function getCategory(id,divId,fieldName){
      var URL = 'response.php';
      $.ajax({
        url:URL,
        data:{'id':id},
        dataType:'json',
        type:'POST',
        beforeSend:function(){  $('#'+divId+'_loader').html('<img src="loading.gif">');},

        success:function(data){
          var select = '<select name="'+fieldName+'" id="'+fieldName+'Id" >';
          select += '<option value="">-SELECT-</option>';
          $.each(data, function(i,cat) {
            select += '<option value="'+cat.id+'">'+cat.name+'</option>';
          });
          select += '</select>';
/*
          alert(divId);
          alert(select);
*/

          $('#'+divId).html(select);
        },
        complete:function(){
          // here set time out is use less , it is used to show the working of loader
          setTimeout(function(){
              $('#'+divId+'_loader').html('');
          },1000)
        },
        error: function(xhr,status,error) { alert('Error: ' + status) ; }
      });
    }
    //// by default called on page load
    ///getCategory(0,'main_cat_div','maincat');

    $('#maincatId').change(function(){
      $('#sub_cat2_div').html('<select><option>-SELECT-</option></select>');
      var id = $(this).val();
      getCategory(id,'sub_cat_div','subcat1');
    });

    $('#subcat1Id').live('change',function(){
      var id = $(this).val();
      getCategory(id,'sub_cat2_div','subcat2');
    });

  });
</script>



<div class="main">
<form method="post">
  <div class="child">
    <span >Main Category</span>
    <span id="main_cat_div"><select id="maincatId" name="maincat"><option value="">-SELECT-</option><option value="1">programming lang</option><option value="2">electronics</option><option value="3">country</option></select></span>
    <span id="main_cat_div_loader"></span>
  </div>

  <div class="child">
    <span>Sub Category-1</span>
    <span id="sub_cat_div"><select><option>-SELECT-</option></select></span>
    <span id="sub_cat_div_loader"></span>
  </div>

  <div class="child">
    <span>Sub Category-2</span>
    <span id="sub_cat2_div"><select><option>-SELECT-</option></select></span>
    <span id="sub_cat2_div_loader"></span>
  </div>
  <input type="submit" value="check it !">
</form>
</div>
